<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><v-for> 数据遍历</v-for>
    计算</title>
</head>
<body>
    <div id="app">
        <h2>{{msg}}</h2>
        <table border="1px" v-if="cart.length!=0">
        <tr>
            <td>编号</td>
            <td>商品名称</td>
            <td>单价</td>
            <td>数量</td>
            <td>小计</td>
            <td>操作</td>
        </tr>
        <tr v-for="p in cart" :key="p.id">
            <td>{{p.id}}</td>
            <td>{{p.name}}</td>
            <td>{{p.price}}</td>
            <td>{{p.count}}</td>
            <td>
                <button @click="addCount(p)">+</button>
                {{p.price*p.count}}
                <button @click="subractCount(p)":disabled="p.count<=1">-</button>
            </td>
            <td><button @click="del(p.id)">删除</button></td>
        </tr>
    </table>
    <span v-if="cart.length==0">购物车中暂无商品,请去购物</span>
    <!--方法要加括号 -->
    <h2>总计:{{totalPrice()}}</h2>
    <h2>总计:{{totalPrice()}}</h2>
    <h2>总计:{{totalPrice()}}</h2>
    <h2>总计:{{totalPrice()}}</h2>
    <hr></hr>
    <!--计算属性不加括号 -->
    <h2>总计:{{total}}</h2>
    <h2>总计:{{total}}</h2>
    <h2>总计:{{total}}</h2>
    <h2>总计:{{total}}</h2>
    </div>
</body>
</html>
<script src="./js/2.7.14_dist_vue.js"></script>
<script>
    new Vue({
        el:"#app",
        data:{
            msg:"hello Vue!",
            cart:[
                {id:'1',name:'苹果',price:'8',count:2},
                {id:'2',name:'哈密瓜',price:'18',count:1},
                {id:'3',name:'老村长',price:25,count:2},
            ],
        },
        methods: {
            del(id){
                this.cart = this.cart.filter((item)=> item.id !=id);
                //find  filter reduce
            },

            addCount(p){
                p.count++;
            },
            subractCount(p){
                if(p.count >1){
                    p.count--;
            }else{
                alert("数量不能少于1");
            }
        } ,
        //计算总价
        totalPrice(){
            console.log("method-------------------------------")
            //accumulator
            const total = this.cart.reduce((accumulator,product)=>{
                return accumulator + product.price * product.count;
            },0);
            return total;
        },
        
        },
        //计算属性
        computed:{
            total(){
                console.log("method-------------------------------")
                return this.totalPrice();
            }
        },
    })
</script>